<template>
  <el-card v-loading="loading" class="dish-detail-container">
    <el-button icon="arrow-left" size="small" style="margin-bottom: 10px" type="warning" @click="router.go(-1)">返回
    </el-button>
    <div v-if="dishDetail">
      <MerchantCard :merchant="dishDetail.merchant"/>

      <!-- 菜品主要信息 -->
      <el-row :gutter="30">
        <!-- 左侧图片轮播 -->
        <el-col :span="12">
          <el-card class="image-card" shadow="never">
            <el-carousel
                :autoplay="true"
                :interval="4000"
                height="400px"
                type="card"
            >
              <el-carousel-item v-for="(image, index) in dishDetail.images" :key="index">
                <el-image
                    :initial-index="index"
                    :preview-src-list="dishDetail.images.map(img => img.url)"
                    :src="image.url"
                    fit="cover"
                    style="width: 100%; height: 100%"
                />
              </el-carousel-item>
            </el-carousel>
            <el-image
                v-if="!dishDetail.images || dishDetail.images.length === 0"
                :preview-src-list="[dishDetail.image?.url]"
                :src="dishDetail.image?.url"
                fit="cover"
                style="width: 100%; height: 400px"
            />
          </el-card>
        </el-col>

        <!-- 右侧菜品信息 -->
        <el-col :span="12">
          <el-card class="info-card" shadow="never">
            <div class="dish-header">
              <h1 class="dish-title">{{ dishDetail.name }}</h1>
              <div class="dish-tags">
                <el-tag v-if="dishDetail.hot" size="large" type="danger">热销</el-tag>
                <el-tag v-if="dishDetail.new" size="large" style="margin-left: 8px" type="success">新品</el-tag>
                <el-tag v-if="dishDetail.discount < 1" size="large" style="margin-left: 8px" type="warning">
                  {{ Math.floor(dishDetail.discount * 10) }}折
                </el-tag>
              </div>
            </div>

            <p class="dish-description">{{ dishDetail.description }}</p>

            <!-- 评分和销量 -->
            <div class="rating-sales-info">
              <div>
                <el-rate
                    v-model="dishDetail.rating"
                    disabled
                    score-template="{value}分"
                    show-score
                    text-color="#ff9900"
                />
              </div>
              <div class="sales-info">
                <el-icon>
                  <TrendCharts/>
                </el-icon>
                <span>已售 {{ dishDetail.sales }} 份</span>
              </div>
            </div>

            <!-- 价格信息 -->
            <div class="price-section">
              <div class="price-info">
                <span class="current-price">¥{{ (dishDetail.price * dishDetail.discount).toFixed(2) }}</span>
                <span v-if="dishDetail.discount < 1" class="original-price">¥{{ dishDetail.price.toFixed(2) }}</span>
              </div>
              <div class="stock-info">
                <el-icon>
                  <Box/>
                </el-icon>
                <span>库存 {{ dishDetail.stock }} 份</span>
              </div>
            </div>

            <!-- 数量选择 -->
            <div class="quantity-section">
              <span class="quantity-label">数量：</span>
              <el-input-number
                  v-model="quantity"
                  :max="dishDetail.stock"
                  :min="1"
                  size="large"
                  style="width: 120px"
              />
            </div>

            <!-- 操作按钮 -->
            <div class="action-section">
              <el-button
                  :icon="dishDetail.collect ? StarFilled : Star"
                  :type="dishDetail.collect ? 'warning' : 'default'"
                  size="large"
                  @click="handleToggleCollect"
              >
                {{ dishDetail.collect ? '已收藏' : '收藏' }}
              </el-button>
              <el-button
                  :disabled="dishDetail.stock <= 0"
                  :icon="ShoppingCart"
                  size="large"
                  type="primary"
                  @click="handleAddToCart"
              >
                加入购物车
              </el-button>
              <el-button
                  :disabled="dishDetail.stock <= 0"
                  :icon="ShoppingBag"
                  size="large"
                  type="danger"
                  @click="handleBuyNow"
              >
                立即购买
              </el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 用户评论 -->
      <el-card class="review-card" shadow="never" style="margin-top: 20px">
        <template #header>
          <div style="display: flex; align-items: center">
            <el-icon style="margin-right: 8px">
              <ChatDotRound/>
            </el-icon>
            <span>用户评价 ({{ dishDetail.reviewList?.length || 0 }})</span>
          </div>
        </template>

        <div v-if="dishDetail.reviewList && dishDetail.reviewList.length > 0">
          <div
              v-for="review in dishDetail.reviewList"
              :key="review.id"
              class="review-item"
          >
            <div class="review-header">
              <el-avatar
                  :icon="UserFilled"
                  :size="40"
                  :src="review.userAvatar"
              />
              <div class="review-user-info">
                <div class="user-name">{{ review.userName }}</div>
                <div class="review-rating">
                  <el-rate
                      v-model="review.rating"
                      disabled
                      size="small"
                  />
                  <span class="review-time">{{ review.createTime }}</span>
                </div>
              </div>
            </div>
            <div class="review-content">{{ review.content }}</div>
          </div>
        </div>
        <el-empty v-else description="暂无评价"/>
      </el-card>

      <!-- 猜你喜欢 -->
      <el-card v-if="recommendList.length > 0" class="recommend-card" shadow="never" style="margin-top: 20px">
        <template #header>
          <div style="display: flex; align-items: center">
            <el-icon style="margin-right: 8px">
              <Star/>
            </el-icon>
            <span>猜你喜欢</span>
          </div>
        </template>
        <el-row :gutter="20">
          <el-col v-for="dish in recommendList" :key="dish.id" :span="6">
            <DishCard
                :dish="dish"
                @add-to-cart="handleRecommendAddToCart"
                @add-to-favorite="handleRecommendAddToFavorite"
                @click-detail="handleRecommendClickDetail"
            />
          </el-col>
        </el-row>
      </el-card>
    </div>

    <OrderCreateDialog ref="orderRef"></OrderCreateDialog>
  </el-card>
</template>

<script setup>
import {onMounted, ref} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import {ElMessage} from 'element-plus'
import {
  Box,
  ChatDotRound,
  ShoppingBag,
  ShoppingCart,
  Star,
  StarFilled,
  TrendCharts,
  UserFilled
} from '@element-plus/icons-vue'
import request from '@/utils/request'
import DishCard from '@/components/DishCard.vue'
import MerchantCard from '@/components/MerchantCard.vue';
import OrderCreateDialog from "@/components/OrderCreateDialog.vue"; // <-- 引入新组件

const route = useRoute()
const router = useRouter()

// 响应式数据
const loading = ref(false)
const dishDetail = ref(null)
const recommendList = ref([])
const quantity = ref(1)

// 获取菜品详情
const handleGetDishDetail = async () => {
  loading.value = true
  const dishId = route.query.id
  dishDetail.value = await request.get(`/dish/${dishId}`)
  loading.value = false
}

// 获取推荐菜品
const handleGetRecommendList = async () => {
  recommendList.value = await request.post('/dish/recommend')
}

// 切换收藏状态
const handleToggleCollect = async () => {
  const data = await request.post('/collect', {businessType: 1, businessId: dishDetail.value.id})
  dishDetail.value.collect = !dishDetail.value.collect
  ElMessage.success(data)
}

// 加入购物车
const handleAddToCart = async () => {
  await request.post('/cart', {
    businessType: 1,
    businessId: dishDetail.value.id,
    count: quantity.value
  })
  ElMessage.success(`已添加 ${quantity.value} 份到购物车`)
}

// 立即购买
const orderRef = ref(null)
const handleBuyNow = async () => {
  const dish = dishDetail.value
  dish.count = quantity.value
  dish.businessId = dish.id
  orderRef.value.open([dish], 1)
}

// 推荐菜品操作
const handleRecommendAddToCart = async (dish) => {
  await request.post('/cart', {dishId: dish.id, count: 1})
  ElMessage.success('已添加到购物车')
}

const handleRecommendAddToFavorite = async (dish) => {
  const msg = await request.post('/collect', {businessType: 1, businessId: dish.id})
  ElMessage.success(msg)
}

const handleRecommendClickDetail = (dish) => {
  router.push({
    path: '/userHome/dishDetail',
    query: {id: dish.id}
  })
  // 重新加载当前页面数据
  handleGetDishDetail()
}

// 初始化
onMounted(async () => {
  await handleGetDishDetail()
  await handleGetRecommendList()
})
</script>

<style scoped>
.dish-detail-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.image-card, .info-card, .review-card, .recommend-card {
  border-radius: 12px;
}

.dish-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.dish-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0;
  flex: 1;
}

.dish-tags {
  display: flex;
  gap: 8px;
}

.dish-description {
  font-size: 16px;
  color: #606266;
  line-height: 1.6;
  margin-bottom: 20px;
}

.rating-sales-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.sales-info {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #909399;
}

.price-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 16px;
  background: #fff5f5;
  border-radius: 8px;
  border-left: 4px solid #ff4757;
}

.current-price {
  font-size: 28px;
  font-weight: 600;
  color: #ff4757;
}

.original-price {
  font-size: 18px;
  color: #909399;
  text-decoration: line-through;
  margin-left: 12px;
}

.stock-info {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #606266;
}

.quantity-section {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
}

.quantity-label {
  font-size: 16px;
  font-weight: 500;
  margin-right: 16px;
}

.action-section {
  display: flex;
  gap: 16px;
}

.action-section .el-button {
  flex: 1;
  height: 48px;
  font-size: 16px;
}

/* 评论样式 */
.review-item {
  padding: 20px 0;
  border-bottom: 1px solid #ebeef5;
}

.review-item:last-child {
  border-bottom: none;
}

.review-header {
  display: flex;
  gap: 12px;
  margin-bottom: 12px;
}

.review-user-info {
  flex: 1;
}

.user-name {
  font-weight: 500;
  margin-bottom: 4px;
}

.review-rating {
  display: flex;
  align-items: center;
  gap: 12px;
}

.review-time {
  font-size: 12px;
  color: #909399;
}

.review-content {
  font-size: 14px;
  line-height: 1.6;
  color: #606266;
  margin-left: 52px;
}

/* 轮播图样式 */
:deep(.el-carousel__item) {
  border-radius: 8px;
  overflow: hidden;
}

/* 轮播图图片宽度修复（从之前的问题中复制过来，确保效果） */
:deep(.el-carousel--card .el-carousel__item) {
  width: 100% !important; /* 强制每个卡片项占据轮播图的全部宽度 */
  left: 0 !important; /* 将卡片项左对齐到容器 */
  transform: translateX(0) scale(1) !important; /* 移除卡片模式的缩放和位移效果 */
  margin: 0 !important; /* 移除卡片之间的默认边距 */
}

/* 可选：美化轮播图指示器和箭头，使其在样式改变后仍然协调。
*/
:deep(.el-carousel__indicator button) {
  background-color: rgba(0, 0, 0, 0.3) !important; /* 默认指示器颜色 */
}

:deep(.el-carousel__indicator.is-active button) {
  background-color: #409EFF !important; /* 活跃指示器颜色，与 Element Plus 主题色一致 */
}

:deep(.el-carousel__arrow) {
  background-color: rgba(0, 0, 0, 0.4) !important; /* 箭头背景 */
  color: #fff !important; /* 箭头颜色 */
  border-radius: 50% !important; /* 圆形箭头 */
  opacity: 0.8 !important; /* 默认透明度 */
}

:deep(.el-carousel__arrow:hover) {
  background-color: rgba(0, 0, 0, 0.6) !important; /* 鼠标悬停时的背景 */
  opacity: 1 !important;
}

</style>